import { login, logout } from '@/api/user'
import {getToken, setToken, removeToken, setUser, getUser, removeUser} from '@/utils/auth'
import router from '@/router'
import {disConnect} from "@/socket";

const user = {
  state: {
    token: getToken(),
    name: '',
    avatar: '',
    roles: [],
    permissions: []
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_NAME: (state, name) => {
      state.name = name
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    },
    SET_PERMISSIONS: (state, permissions) => {
      state.permissions = permissions
    }
  },

  actions: {
    // 登录
    Login({commit}, userInfo) {
      const username = userInfo.username
      const password = userInfo.password
      return new Promise((resolve, reject) => {
        login(username, password).then(res => {
          const token = res.data.token
          const loginusername = res.data.username
          const avatar = res.data.userProfile
          setToken(token)
          setUser(res.data)
          commit('SET_TOKEN', token)
          commit('SET_NAME', loginusername)
          commit('SET_AVATAR', avatar)
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },



    // 退出系统
    LogOut({commit, state}) {
      return new Promise((resolve, reject) => {
        logout(state.token).then(() => {
          commit('SET_TOKEN', '')
          commit('SET_ROLES', [])
          commit('SET_PERMISSIONS', [])
          removeToken()
          removeUser()
          router.push('/login')
          disConnect()
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 前端 登出
    FedLogOut({commit}) {
      return new Promise(resolve => {
        commit('SET_TOKEN', '')
        removeToken()
        resolve()
      })
    }
  }
}


export default user
